package com.yc.qunxing.web;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yc.qunxing.entity.Orders;
import com.yc.qunxing.entity.UserCoupons;
import com.yc.qunxing.entity.Users;
import com.yc.qunxing.properties.JwtProperties;
import com.yc.qunxing.result.Result;
import com.yc.qunxing.service.IUserCouponsService;
import com.yc.qunxing.service.IUsersService;
import com.yc.qunxing.utils.AppJwtUtil;
import com.yc.qunxing.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 鹏哥
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {


    @Autowired
    private IUsersService iUsersService;
    @Autowired
    private IUserCouponsService iUserCouponsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/getById")
    public Result<Users> GetById(@RequestParam Integer userId){
        Users userDemo1 = iUsersService.getById(userId);
        return Result.success(userDemo1);
    }

    @PostMapping("/login")
    public Result<Users> LoginedUser(HttpServletRequest req, HttpServletResponse resp,@RequestBody Users users) throws IOException {
        // 从请求体中获取手机号和密码
        String phoneNumber = users.getPhoneNumber();
        String password = users.getPassword();
        String verification = users.getVerification();
        int t=doPics(req,resp,verification);
        if(t==0){
            return Result.error("验证码错误");
        }
        // 构建查询条件
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number", phoneNumber).eq("password", password).eq("status", "1");

        // 根据手机号和密码查询用户信息
        Users user = iUsersService.getOne(queryWrapper);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(
                JwtProperties.adminSecretKey,
                JwtProperties.adminTtl,
                claims);
/*        String token = AppJwtUtil.getToken(user.getId().longValue());*/
        user.setToken(token);
        if (user != null) {
            // 登录成功
            return Result.success(user);
        } else {
            // 登录失败
            return Result.error("手机号或密码错误");
        }
    }

    @PostMapping("/register")
    public Result<String> RegisterUser(HttpServletRequest req, HttpServletResponse resp,@RequestBody Users users) throws IOException {
        String verification = users.getVerification();
        int t=doPics(req,resp,verification);
        if(t==0){
            return Result.error("验证码错误");
        }
        return iUsersService.registerUser(users);
    }

    @PutMapping("/updateRnum/{userIdInt}")
    public Result UpdateRnum(@PathVariable("userIdInt") Integer id) {
        iUsersService.updateRaffleNum(id);

        return Result.success("更新成功");
    }

    @PostMapping("updateCoupon")
    public Result UpdateCoupon(@RequestBody UserCoupons userCoupons){
        Integer userId = userCoupons.getUserId();
        String couponName = userCoupons.getCouponName();
        QueryWrapper<UserCoupons> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("coupon_name", couponName);
        UserCoupons existingCoupon = iUserCouponsService.getOne(queryWrapper);

/*        if (existingCoupon != null) {
            // 如果数据已存在，更新 couponNum 字段加1
            UpdateWrapper<UserCoupons> updateWrapper = new UpdateWrapper<>();
            updateWrapper.setSql("coupon_num = coupon_num + 1")
                    .eq("user_id", userId)
                    .eq("coupon_name", couponName);
            iUserCouponsService.update(updateWrapper);
            return Result.success("更新成功");
        } else {*/
            // 如果数据不存在，插入新数据
/*            userCoupons.setValidStart(LocalDateTime.now());
            userCoupons.setValidUntil(LocalDateTime.now().plusDays(15));*/
            userCoupons.setCouponNum(1);
            iUserCouponsService.save(userCoupons);
            return Result.success("插入成功");
/*        }*/
    }
    @PutMapping("updateCouponNum")
    public Result UpdateCouponNum(@RequestParam Integer id) {
        boolean updated = iUserCouponsService.updateCouponNum(id);
        if (updated) {
            // 更新成功后，删除 couponNum 为 0 的记录
            iUserCouponsService.deleteZeroCouponNumRecords();
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }
    @PutMapping("updatePic")
    public Result UpdataPic(@RequestBody Users users){
        iUsersService.updateById(users);
        return Result.success("修改图片成功");
    }
    @PostMapping("/changePassword")
    public Result<Map<String, Object>> changePassword(@RequestBody Map<String, Object> request) {
        String userIdStr = (String) request.get("userId");
        Integer userId = Integer.parseInt(userIdStr); // 进行类型转换

        String originalPassword = (String) request.get("originalPassword");
        String newPassword = (String) request.get("newPassword");

        Map<String, Object> response = new HashMap<>();
        if (iUsersService.verifyOriginalPassword(userId, originalPassword)) {
            iUsersService.changePassword(userId, newPassword);
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }

    @PostMapping("/changePhone")
    public Result<Map<String, Object>> changePhone(@RequestBody Map<String, Object> request) {
        String userIdStr = (String) request.get("userId");
        Integer userId = Integer.parseInt(userIdStr); // 进行类型转换
        String phone = (String) request.get("phone");

        Map<String, Object> response = new HashMap<>();
        if (iUsersService.changePhone(userId, phone)) {
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }

    @PostMapping("/changeName")
    public Result<Map<String, Object>> changeName(@RequestBody Map<String, Object> request) {
        String userIdStr = (String) request.get("userId");
        Integer userId = Integer.parseInt(userIdStr); // 进行类型转换
        String name = (String) request.get("userName");

        Map<String, Object> response = new HashMap<>();
        if (iUsersService.changeName(userId, name)) {
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }

    @PostMapping("/sendVerificationCode")
    public Result<Map<String, Object>> sendVerificationCode(@RequestBody Map<String, Object> request) {
        String userIdStr = (String) request.get("userId");
        Integer userId = Integer.parseInt(userIdStr); // 进行类型转换
        String email = (String) request.get("email");
        String code = (String) request.get("code");

        Map<String, Object> response = new HashMap<>();
        if (iUsersService.sendVerificationCode(userId, email, code)) {
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }

    @PostMapping("/changeEmail")
    public Result<Map<String, Object>> changeEmail(@RequestBody Map<String, Object> request) {
        String userIdStr = (String) request.get("userId");
        Integer userId = Integer.parseInt(userIdStr); // 进行类型转换
        String newEmail = (String) request.get("newEmail");

        Map<String, Object> response = new HashMap<>();
        if (iUsersService.changeEmail(userId, newEmail)) {
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }

    @GetMapping("/getCoupons")
    public Result<List<UserCoupons>> GetCoupons(@RequestParam Integer userId){
        List<UserCoupons> coupons = iUserCouponsService.getCouponsByUserId(userId);
        return Result.success(coupons);
    }
    @GetMapping("/getUserByManager")
    public Result<PageInfo<Users>> GetUserByManager( @RequestParam(defaultValue = "1") Integer page,
                                                     @RequestParam(defaultValue = "10") Integer size,
                                                     @RequestParam(required = false) String keyword,
                                                     @RequestParam(required = false) String keywordOrder) {
        String cacheKey = "getUserByManager_" + page + "_" + size + "_" + keyword + "_" + keywordOrder;

        PageInfo<Users> cachedPageInfo = (PageInfo<Users>) redisTemplate.opsForValue().get(cacheKey);

        if (cachedPageInfo != null) {
            // 如果缓存命中，则直接返回缓存数据
            return Result.success(cachedPageInfo);
        }
        PageHelper.startPage(page, size);
        List<Users> usersList = iUsersService.getUserByManager(keyword,keywordOrder);
        PageInfo<Users> pageInfo = new PageInfo<>(usersList);
        redisTemplate.opsForValue().set(cacheKey, pageInfo, 5, TimeUnit.MINUTES);
        return Result.success(pageInfo);
    }
    @PutMapping("/updateUserStatus")
    public Result<String> UpdateUserStatus(@RequestBody Users users){
        iUsersService.updateById(users);
        clearUserByManagerCache();
        return Result.success("修改状态成功");
    }
    private void clearUserByManagerCache() {
        String cacheKeyPattern = "getUserByManager_*";
        Set<String> keys = redisTemplate.keys(cacheKeyPattern);
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
    protected int doPics(HttpServletRequest req, HttpServletResponse resp, String usafe) throws IOException {
        HttpSession session=req.getSession();
        String sessionId = session.getId();
        System.out.println("sessionId = " + sessionId);
        /*String scpat = (String) session.getAttribute("verityCode");*/
        String scpat = (String) redisTemplate.opsForValue().get(sessionId);
        System.out.println("who:"+usafe+","+scpat);
        if(scpat != null && scpat.equals(usafe)){
            return 1;
        }else{
            return 0;
        }
    }
}
